<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item label="预订编号" prop="numberId">
          <el-input
            v-model="queryParams.numberId"
            placeholder="请输入预订编号"
            clearable
            style="width: 240px"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
        </el-form-item>
      </el-form>
   <!-- <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:config:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:config:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:config:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:config:export']"
        >导出</el-button>
      </el-col>
     <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-refresh"
          size="mini"
          @click="handleRefreshCache"
          v-hasPermi="['system:config:remove']"
        >刷新缓存</el-button>
      </el-col> 
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>-->

    <el-table v-loading="loading" :data="configList" @selection-change="handleSelectionChange"> 
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" width="55" align="center" prop="id" >
        <template slot-scope="scope">
          <!-- 计算序号 -->
          {{ (queryParams.pageNum - 1) * queryParams.pageSize+ scope.$index + 1  }}
        </template>
      </el-table-column>
      <el-table-column label="预定编号" align="center" prop="numberId" :show-overflow-tooltip="true" />
      <el-table-column label="姓名" align="center" prop="reserveName" :show-overflow-tooltip="true" />
      <el-table-column label="电话" align="center" prop="reservePhone" :show-overflow-tooltip="true" />
      <el-table-column label="房间编号" align="center" prop="roomId" :show-overflow-tooltip="true" />
      <el-table-column label="房间类型" align="center" prop="houseType" :show-overflow-tooltip="true" />
      <el-table-column label="入住天数" align="center" prop="inDays" :show-overflow-tooltip="true" />
      <el-table-column label="支付金额" align="center" prop="reserveDeposit" :show-overflow-tooltip="true" />
      <el-table-column label="支付方式" align="center" prop="reservePrice" :show-overflow-tooltip="true" />
      <el-table-column label="订单来源" align="center" prop="reserveType" :show-overflow-tooltip="true" />
      <el-table-column label="预定入住时间" align="center" prop="dateIn" width="160">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.dateIn) }}</span>
        </template>
      </el-table-column>
       <el-table-column label="退房时间" align="center" prop="dateOut" width="160">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.dateOut) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="120" fixed="right" class-name="small-padding fixed-width" >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-s-claim"
            @click="handleCheckIn(scope.row)"
          >入住</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-s-release"
            @click="handleCheckOut(scope.row)"
            v-hasPermi="['system:orderManage:checkOut']"
          >退订</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:config:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:orderManage:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改参数配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="姓名" prop="reserveName" >
          <el-input v-model="form.reserveName" placeholder="请输入预定人姓名"  :disabled="isCheckOut"/>
        </el-form-item>
        <el-form-item label="预定电话" prop="reservePhone">
          <el-input v-model="form.reservePhone" placeholder="请输入预定电话" :disabled="isCheckOut" />
        </el-form-item>
        <el-form-item label="房间编号" prop="roomId">
          <el-select v-model="form.roomId" placeholder="请选择房间编号" style="width: 340px" :disabled="isCheckOut" @change="handleRoomIdChange">
            <el-option
              v-for="item in roomIdOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="房间类型" prop="houseType">
          <el-select v-model="form.houseType" placeholder="请选择房间类型" style="width: 340px" disabled>
            <el-option
              v-for="item in houseTypeOptions"            
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="入住天数" prop="inDays">
          <el-input v-model="form.inDays" placeholder="请输入入住天数" :disabled="isCheckOut"   @input="calculateDeposit" />
        </el-form-item>
        <el-form-item label="支付金额" prop="reserveDeposit">
          <el-input v-model="form.reserveDeposit" placeholder="请输入支付金额" disabled />
        </el-form-item>
        <el-form-item label="支付方式" prop="reservePrice" v-if="!isCheckOut">
          <!-- <el-input v-model="form.reservePrice" placeholder="请输入支付金额" /> -->
          <el-select v-model="form.reservePrice" placeholder="请选择支付方式"  :disabled="isCheckOut" style="width: 340px">
            <el-option
              v-for="item in reservePriceOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="订单来源" prop="reserveType" >
          <!-- <el-input v-model="form.reserveType" placeholder="请输入订单来源" /> -->
          <el-select v-model="form.reserveType" placeholder="请选择订单来源" :disabled="isCheckOut" style="width: 340px" >
            <el-option
              v-for="item in reserveTypeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
         <el-form-item label="预订入住时间" prop="dateIn" v-if="!isCheckOut">
          <el-date-picker
            v-model="form.dateIn"
            style="width: 340px"
            type="datetime"
            :disabled="isCheckOut"
            start-placeholder="开始日期"
            :default-time="['00:00:00']"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="退订金额" prop="reserveDeposit" v-if="isCheckOut" >
          <el-input v-model="form.reserveDeposit" placeholder="请输入退订金额" :disabled="isCheckOut" />
        </el-form-item>
        <el-form-item label="退订原因" prop="reserveReason" v-if="isCheckOut">
          <el-select v-model="form.reserveReason" placeholder="请选择退订原因" style="width: 340px" @change="handleRoomIdChange">
            <el-option
              v-for="item in reserveReasonOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listConfig, getConfigKey,addConfig, updateConfig,checkInConfig,checkOutConfig,delConfig,  refreshCache } from "@/api/system/config";
import { listGuestRoom as roomInfoListConfig} from "@/api/system/guestRoom";

export default {
  name: "Config",
  dicts: ['sys_yes_no'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 参数表格数据
      configList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // // 日期范围
      // dateIn: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        configName: undefined,
        configKey: undefined,
        configType: undefined
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        reserveName: [
          { required: true, message: "姓名不能为空", trigger: "blur" }
        ],
        reservePhone: [
          { required: true, message: "电话不能为空", trigger: "blur" }
        ],
        roomId: [
          { required: true, message: "房间编号不能为空", trigger: "blur" }
        ],
        houseType: [
          { required: true, message: "房间类型不能为空", trigger: "blur" }
        ],
        inDays: [
          { required: true, message: "入住天数不能为空", trigger: "blur" }
        ],
        reserveReason: [
          { required: true, message: "退订原因不能为空", trigger: "blur" }
        ]
      },
      roomIdOptions: [
        // { value: '101', label: '101号房间' },
        // { value: '102', label: '102号房间' },
        // { value: '103', label: '103号房间' }
      ],
      houseTypeOptions: [
        // { value: 'single', label: '单人间' },
        // { value: 'double', label: '双人间' },
        // { value: 'suite', label: '套房' }
      ],
      roomInfoMap: {
        // '101': { houseType: 'single', roomPrice: 200 },
        // '102': { houseType: 'double', roomPrice: 300 },
        // '103': { houseType: 'suite', roomPrice: 500 }
      },
      reservePriceOptions: [
        { value: '微信', label: '微信' },
        { value: '支付宝', label: '支付宝' },
        { value: '网银', label: '网银' },
        { value: '现金', label: '现金' }
      ],
      reserveTypeOptions:[
        { value: '美团', label: '美团' },
        { value: '携程', label: '携程' },
        { value: '飞猪', label: '飞猪' },
        { value: '线下', label: '线下' }
      ],
      reserveReasonOptions:[
      { value: '其他原因', label: '其他原因' },
        { value: '行程有误', label: '行程有误' },
        { value: '天气原因', label: '天气原因' },
        { value: '选错房型', label: '选错房型' }
      ],
      isCheckOut:false
    };
  },
  created() {
    this.getList();
    this.getRoomInfoList();
  },
  methods: {
    /** 查询参数列表 */
    getList() {
      this.loading = true;
      listConfig(this.addDateRange(this.queryParams, this.dateIn)).then(response => {
          this.configList = response.rows;
          this.total = response.total;
          this.loading = false;
        }
      );
    },
    //客房信息
    getRoomInfoList() {
      this.loading = true;
      roomInfoListConfig(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
        if (response.rows.length > 0) {
          const roomIdOptions = [];
          const houseTypeSet = new Set();
          const roomInfoMap = {};

          response.rows.forEach(element => {
            // 组装 roomIdOptions
            roomIdOptions.push({
              value: element.numberId,
              label: element.numberId
            });

            // 记录房间类型
            houseTypeSet.add(element.roomType);

            // 组装 roomInfoMap
            roomInfoMap[element.numberId] = {
              houseType: element.roomType,
              roomPrice: element.roomPrice
            };
          });

          // 组装 houseTypeOptions
          const houseTypeOptions = Array.from(houseTypeSet).map(type => {
            return { value: type, type };
          });

          // 更新组件数据
          this.roomIdOptions = roomIdOptions;
          this.houseTypeOptions = houseTypeOptions;
          this.roomInfoMap = roomInfoMap;
        }
        this.loading = false;
      });
    },

    handleRoomIdChange() {
      const selectedRoomId = this.form.roomId;
      const roomInfo = this.roomInfoMap[selectedRoomId];
      if (roomInfo) {
        this.form.houseType = roomInfo.houseType;
        this.calculateDeposit();
      } else {
        this.form.houseType = null;
        this.form.reserveDeposit = null;
      }
    },

    calculateDeposit() {
      const selectedRoomId = this.form.roomId;
      const roomInfo = this.roomInfoMap[selectedRoomId];
      const inDays = parseInt(this.form.inDays);
      if (roomInfo &&!isNaN(inDays)) {
        this.form.reserveDeposit = roomInfo.roomPrice * inDays;
      } else {
        this.form.reserveDeposit = null;
      }
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.isCheckOut = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        reserveName: undefined,
        reservePhone: undefined,
        reserveType: undefined,
        inDays: "1",
        houseType: undefined,
        roomId: undefined,
        dateIn:new Date(),
        reservePrice:"微信",
        reserveType:'美团',
        reserveReason:"其他原因"
        // dateOut:undefined,
        // remark: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    handleDateChange(date) {
      if (date) {
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        const hours = String(date.getHours()).padStart(2, '0');
        const minutes = String(date.getMinutes()).padStart(2, '0');
        const seconds = String(date.getSeconds()).padStart(2, '0');
        this.storedDate = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
      } else {
        this.storedDate = '';
      }
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "新增预订订单";
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.configId)
      this.single = selection.length!=1
      this.multiple = !selection.length
    },
    /** 入住按钮操作 */
    handleCheckIn(row) {
      this.reset();
      const numberId = row.numberId || this.ids;
      checkInConfig(numberId).then(response => {
        this.getList();
        this.$modal.msgSuccess("入住成功");
      });
    },
    //退订
    handleCheckOut(row) {
      // const reserveName = row.reserveName || "";
      // const numberId = row.numberId || this.ids;
      // this.$modal.confirm('确认退订 ' + reserveName + ' 的预定订单吗？').then(function() {
      //     return checkOutConfig(numberId);
      //   }).then(() => {
      //     this.getList();
      //     this.$modal.msgSuccess("退订成功");
      //   }).catch(() => {});

      this.reset();
      const numberId = row.numberId || this.ids
      getConfigKey(numberId).then(response => {
        this.form = response.rows[0];
        this.open = true;
        this.isCheckOut = true;
        this.title = "退订预定订单";
      });
    },
    //修改
    handleUpdate(row) {
      this.reset();
      const numberId = row.numberId || this.ids
      getConfigKey(numberId).then(response => {
        this.form = response.rows[0];
        this.open = true;
        this.title = "修改预订订单";
      });
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.isCheckOut ) {
            checkOutConfig(this.form).then(response => {
              this.$modal.msgSuccess("退订成功");
              this.open = false;
              this.isCheckOut = false;
              this.getList();
            });
            return;
          } 
          if (this.form.numberId != undefined) {
            updateConfig(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addConfig(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const reserveName = row.reserveName || "";
      const numberId = row.numberId || this.ids;
      this.$modal.confirm('确认删除 ' + reserveName + ' 的预定订单吗？').then(function() {
          return delConfig(numberId);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/config/export', {
        ...this.queryParams
      }, `config_${new Date().getTime()}.xlsx`)
    },
    /** 刷新缓存按钮操作 */
    handleRefreshCache() {
      refreshCache().then(() => {
        this.$modal.msgSuccess("刷新成功");
      });
    }
  }
};
</script>
